package com.salesmanager.core.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 
 * @author licongchao@gmail.com
 *
 */
public class EncryptionUtil {
	public final static String SHA1 = "SHA1";
	public final static String MD5 = "MD5";

	private static final Logger log = LoggerFactory.getLogger(EncryptionUtil.class); 
	
	public static String getSalt() {
		return RandomStringUtils.randomAlphabetic(20);
	}
	
	public static String encodeWithSalt(String algorithm, String str, String salt) {
		if (algorithm.equals(SHA1)) {
			return DigestUtils.shaHex(str + (salt == null ? getSalt() : salt));
		} else if (algorithm.equals(MD5)) {
			return DigestUtils.md5Hex(str + (salt == null ? getSalt() : salt));
		} else
			throw new RuntimeException("unSupported algorithm :" + algorithm);
	}
	
	public static String encode(String algorithm, String str){
		if (algorithm.equals(SHA1)) {
			return DigestUtils.shaHex(str);
		} else if (algorithm.equals(MD5)) {
			return DigestUtils.md5Hex(str);
		} else
			throw new RuntimeException("unSupported algorithm :" + algorithm);
	}
	
	public static boolean checkWithSha1(String comparedStr, String str, String salt){
		return check(comparedStr, SHA1, str, salt);
	}

//	public static boolean checkWithMD5(String comparedStr, String str, String salt){
//		return check(comparedStr, MD5, str, salt);
//	}
	
	 public static boolean check(String comparedStr, String algorithm, String str, String salt){
		 return comparedStr.equals(encodeWithSalt(algorithm, str, salt));
	 }
	 
//	 public static String getMD5(String filePath){
//		 FileInputStream fis = null;
//		try {
//			fis = new FileInputStream(new File(filePath));
//			return DigestUtils.md5Hex(fis);
//		} catch (IOException e) {
//			try {
//				fis.close();
//			} catch (IOException e1) {
//				e1.printStackTrace();
//			}
//			log.error("Got exception while processing md5 with file :"+filePath);
//		}
//		return null;
//	 }
	 
	 public static void main(String[] args) {
		 String password = "admin";
		 String salt = EncryptionUtil.getSalt();
		 System.out.println("salt : "+salt);
		 System.out.println(EncryptionUtil.encodeWithSalt(EncryptionUtil.SHA1, password, salt));
	}
}
